<template>
  <div
    class="app-container"
    element-loading-text="加载中..."
    v-loading.fullscreen="loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    style="background: #fff"
  >
    <!-- <com-title-item :title="required == '1' ? '视频配音' : 'VR转视频'"> -->
    <!-- <com-title-item> -->
    <el-tabs v-model="activeName" @tab-click="handleClick" style="padding: 0 20px" v-show="required == '0'">
      <el-tab-pane label="快速合成(推荐)" name="first"></el-tab-pane>
      <!-- <el-tab-pane label="虚拟拍摄" name="second" v-if="hmDelSummaryInfo.houSubType==1"></el-tab-pane> -->
    </el-tabs>
    <com-title-item title="视频配音" v-show="required == '1'" style="padding: 19px 18px 0"> </com-title-item>
    <div style="padding: 0 30px;">
      <!-- 第一步选图片 -->
      <transition name="fade-line" @after-leave="afterLeaveStep1">
        <div class="page" v-show="stepShow1">
          <!-- 图片转视频 -->
          <div v-if="houImageVO.length">
            <el-checkbox-group
              class="imgs-wrap d-flex ai-center flex-wrap"
              v-model="checkList"
              :max="max"
              v-show="activeName == 'first'"
            >
              <div class="item" v-for="item in houImageVO" :key="item.fileId">
                <el-image class="img" :src="item.url" fit="fit"></el-image>
                <div class="checkbox-content">
                  <el-checkbox :label="item.fileId">{{ "" }}</el-checkbox>
                </div>
              </div>
            </el-checkbox-group>
          </div>
          <div v-else class="text-gray fs-md text-center" style="margin: 50px auto">暂无图片~</div>

          <div style="margin-top: 20px">
            <div class="fs-l">
              共选择<span class="text-blue" style="padding: 0 5px">{{ checkList.length }}</span
              >张图片
            </div>
            <div class="text-gray fs-md" style="margin-top: 10px" v-for="(item, i) in infoList" :key="i">
              {{
                i +
                  1 +
                  ". " +
                  item
                    .replace("min", min)
                    .replace("15", activeName == "first" ? "10" : "15")
                    .replace("max", max)
                    .replace(
                      "添加热点链接场景。（将全景图之间做好关联，比如你想先从客厅切换到卧室，卧室到卫生间等等，需要你自己关联场景）",
                      activeName == "first"
                        ? "请确保合成的图片是室内图，并不带有水印；否则可能造成违规；"
                        : "添加热点链接场景。（将全景图之间做好关联，比如你想先从客厅切换到卧室，卧室到卫生间等等，需要你自己关联场景）",
                    )
              }}
            </div>
          </div>
        </div>
      </transition>

      <!-- 第二步填写配音文案 -->
      <transition name="fade-line" @after-leave="afterLeaveStep2">
        <div class="page" v-show="stepShow2">
          <el-input
            type="textarea"
            :rows="7"
            placeholder="请输入内容"
            v-model="textarea"
            :maxlength="maxCount"
            show-word-limit
          >
          </el-input>

          <div class="d-flex ai-center radio-wrap">
            <div class="radio-item d-flex ai-center flex-1" v-for="item in audioList" :key="item.value">
              <i
                class="fs-xxxl pointer"
                :class="[item.value == voiceType ? 'el-icon-success text-red' : 'el-icon-circle-check text-gray']"
                @click="handleSelect(item.value)"
              ></i>
              <div class="d-flex ai-center flex-1" style="margin-left: 10px;">
                <el-image :src="item.avatar" fit="fit" style="width: 40px; height: 40px"></el-image>
                <div class="flex-1 fs-md" style="margin-left: 10px">
                  <div class="">{{ item.name }}</div>
                  <div class="text-gray ellipsis" v-if="item.audioSrc">示例：您好，欢迎使用树懒经纪人！</div>
                </div>
              </div>
              <el-image
                v-if="item.audioSrc"
                class="pointer"
                :src="item.iconState ? stopImgSrc : playImgSrc"
                fit="fit"
                style="width: 30px; height: 30px"
                @click="handlePlay(item.value)"
              ></el-image>
              <audio v-if="item.audioSrc" ref="demoAudio" :src="item.audioSrc"></audio>
            </div>
          </div>
        </div>
      </transition>

      <!-- 按钮 -->
      <div
        class="d-flex jc-center"
        style="margin-top: 50px"
        v-if="activeName == 'first' || (activeName == 'second' && hmDelSummaryInfo.houSubTypeState == 10)"
      >
        <el-button type="info" @click="handleBack">取消</el-button>
        <el-button type="primary" @click="handleNext" :disabled="required == '0' && checkList.length < min"
          >下一步</el-button
        >
      </div>
    </div>
    <!-- </com-title-item> -->
  </div>
</template>

<script>
import { getHouseInfo, getMemberPower, submitSphereToVideoTask, submitImgsToVideoTask, submitImgsToVideoTaskMq } from "@/api/user";
import comTitleItem from "./com/com-title-item";
import { VR_COMPOUND_VIDEO, VR_COMPOUND_ADD } from "@/config/menuId";
import { mapGetters } from "vuex";

// 一室：2张，二室：3张，三室：4张，4室及以上：5张
/** 选择图片最大数 */
let IMG_SELECT_MAX = 6;
export default {
  components: {
    comTitleItem,
  },
  props: {
    houDelId: {
      type: String,
      default: "",
    },
    //是否一定需要声音 0不需要（配音） 1需要（合成视频可以包括配音）
    required: {
      type: String,
      default: "1",
    },
  },
  data() {
    return {
      loading: false,
      delType: "",
      playImgSrc: require("@/assets/images/icons/play.png"),
      stopImgSrc: require("@/assets/images/icons/stop.png"),
      imgList: [], // VR合成视频的图片列表
      houImageVO: [], // 图片合成视频的图片列表
      hmDelSummaryInfo: {}, //判断是否为VR房源，没有VR不显示 VR合成视频的选项
      checkList: [],
      max: 15,
      min: 3,
      infoList: [
        "一张图片能够播放的时间为15秒；",
        "为了保证视频质量，请选择min张～max张图片进行合成视频",
        "添加热点链接场景。（将全景图之间做好关联，比如你想先从客厅切换到卧室，卧室到卫生间等等，需要你自己关联场景）",
      ],
      textarea: "",
      step: 1,
      stepShow1: false,
      stepShow2: false,
      maxCount: 500,
      voiceType: "2", //暂时恒为2  不添加配音
      audioList: [
        {
          value: "0",
          name: "男声",
          avatar: require("@/assets/images/icons/boy.png"),
          iconState: false,
          audioSrc: require("@/assets/mp3/2.mp3"),
        },
        {
          value: "1",
          name: "女声",
          avatar: require("@/assets/images/icons/girl.png"),
          iconState: false,
          audioSrc: require("@/assets/mp3/1.mp3"),
        },
        {
          value: "2",
          name: "放弃视频配音",
          avatar: require("@/assets/images/icons/no.png"),
        },
      ],
      activeName: "first",
    };
  },

  computed: {
    selectedNum() {
      return this.imgList.filter((v) => v.checked).length;
    },
    ...mapGetters(["sessionUser"]),
  },
  async mounted() {
    this.loading = true;
    const data = await getHouseInfo({ houDelId: this.houDelId });
    let houDelVO = data.content.houDelVO;
    this.room = houDelVO.room;
    this.min = Math.min((this.room || 1) + 3, IMG_SELECT_MAX);
    this.delType = houDelVO.delegationType || "SALES";
    let houImageVO = data.content.houImageVO;
    let newHouImageVO = houImageVO.filter((item) => {
      if (item.tagName != "户型图") {
        return true;
      }
    });
    this.houImageVO = newHouImageVO;
    this.hmDelSummaryInfo = data.content.hmDelSummaryInfo;

    this.loading = false;

    if (this.required == "0") {
      this.step = 1;
      this.stepShow1 = true;
    } else {
      this.step = 2;
      this.stepShow2 = true;
      this.audioList = this.audioList.slice(0, 2);
    }
  },

  methods: {
    async getHouseInfo() {
      const data = await getHouseInfo({ houDelId: this.houDelId });
      let houDelVO = data.content.houDelVO;
      this.min = Math.min((houDelVO.room || 1) + 3, IMG_SELECT_MAX);
      this.delType = houDelVO.delegationType || "SALES";
      this.houImageVO = data.content.houImageVO;
      this.hmDelSummaryInfo = data.content.hmDelSummaryInfo;
    },

    timer() {
      this.getHouseInfo().then(() => {
        if (this.hmDelSummaryInfo.houSubTypeState == "1") {
          setTimeout(() => {
            this.timer();
          }, 1000);
        }
      });
    },
    handlePlay(value) {
      let audio = this.$refs.demoAudio[value];
      if (this.audioList[value].iconState) return;

      this.audioList[value].iconState = true;
      let fn = () => {
        this.audioList[value].iconState = false;
        audio.removeEventListener("ended", fn);
      };
      audio.addEventListener("ended", fn);
      audio.play();
    },
    handleSelect(value) {
      this.voiceType = value;
    },

    async handleNext() {
      // if (this.step == 1) {
      //   this.stepShow1 = false;
      //   this.step = 2;
      // } else {
      this.loading = true;

      try {
        await this.submitSphereToVideoTaskHandler();
        
      } catch (error) {
        
      } 

      this.loading = false;
      // }
    },

    async submitSphereToVideoTaskHandler() {
      let obj = {};
      if (this.activeName == "second" || this.required == "1") {
        obj.delId = this.houDelId;
        obj.taskCode = this.required == "1" ? "videodubbing" : "spheretovideo";
      } else {
        obj.delId = this.houDelId;
      }

      // 合成配音
      if (this.required == "1") {
        obj.dubbed = this.voiceType;

        // 合成视频
      } else {
        if (this.activeName == "first" && this.required == "0") {
          obj.fileIdList = this.checkList;
        } else {
          obj.sceneIdList = this.checkList;
        }
        // if (this.voiceType != "2") {
        obj.dubbed = this.voiceType;
        // }
      }

      // if (this.activeName == "first" && this.required == "0") {
      await submitImgsToVideoTaskMq(obj);
      // } else {
      // var { isSuccess } = await submitSphereToVideoTask(obj);
      // }
      getMemberPower({
        menuId: VR_COMPOUND_VIDEO,
        agentId: this.sessionUser.id,
      });
      const text =
        this.required == "1"
          ? "配音任务已提交，大约需要2到3分钟，请稍后到房源详情查看"
          : "视频合成任务已提交，大概需" +
            (this.activeName == "first" ? "2到3分钟" : "1小时") +
            "，在房源列表页可查看进度";

      return this.$messageBox
        .confirm(text, {
          confirmButtonText: "我知道了",
          showCancelButton: false,
        })
        .finally(() => {
          this.$store.dispatch("tagsView/delView", this.$route);
          this.$router.back();
        });
      
    },

    handleBack() {
      if (this.step == 1 || this.required == "1") {
        this.$store.dispatch("tagsView/delView", this.$route);
        this.$router.back();
      } else {
        this.step = 1;
        this.stepShow2 = false;
      }
    },
    afterLeaveStep1() {
      this.stepShow2 = true;
    },
    afterLeaveStep2() {
      this.stepShow1 = true;
    },
    handleClick(tab, event) {
      if (tab.name == "first") {
        IMG_SELECT_MAX = 6;
        this.min = Math.min((this.room || 1) + 3, IMG_SELECT_MAX);
        this.max = 15;
      } else {
        IMG_SELECT_MAX = 5;
        this.min = Math.min((this.room || 1) + 3, IMG_SELECT_MAX);
        this.max = 9;
      }
      this.checkList = [];
      this.step = 1;
      this.stepShow2 = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  // position: relative;
  min-height: calc(100vh - 85px);
}
.imgs-wrap {
  .item {
    margin: 10px;
    position: relative;
    border: 1px solid rgb(207, 207, 207);
    border-radius: 5px;
    overflow: hidden;
    .img {
      width: 120px;
      height: 120px;
    }
    .checkbox-content {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      background: white;
      padding: 5px;
    }
  }
}

.radio-wrap {
  margin-top: 30px;
  .radio-item {
    border-radius: 5px;
    box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 10px;
    margin-right: 30px;
    padding: 10px;
  }
}

.fade-line-enter-active,
.fade-line-leave-active {
  transition: all 0.5s;
}
.fade-line-enter,
.fade-line-leave-to {
  opacity: 0;
  transform: translateX(36px);
}
</style>
